<template>
	<view class="container">
		<scroll-view scroll-y class="order-detail">
			<!-- 订单状态 -->
			<view class="order-status">
				<view class="status-bg">
					<image src="/static/images/icon/status-bg.png"></image>
				</view>
				<view class="status-text">{{['',i18n.waitingBuyerPay,i18n.waitingForDelivery,i18n.waitingBuyerReceipt,i18n.orderCompleted,i18n.orderCompleted,i18n.orderCancelled,i18n.itInaGroup][status]}}</view>
				<view class="step">
					<view :class="['item',status==2||status==3||status==4||status==5||status==7?'active':'']">
						<view class="select"></view>
						<view class="des">{{i18n.buyerPayment}}</view>
					</view>
					<!-- 自提没有这一项 -->
					<view :class="['item',(dvyType == 1 || dvyType == 4) && (status==3||status==4||status==5) ?'active':'']" v-if="(dvyType == 1 || dvyType == 4)">
						<view class="select"></view>
						<view class="des">{{i18n.merchantShipment}}</view>
					</view>
					<!-- 快递没有这一项 -->
					<view :class="['item',status==3 || status==5?'active':'']" v-if="dvyType == 2">
						<view class="select"></view>
						<view class="des">{{i18n.buyerPickUp}}</view>
					</view>
					<view :class="['item',status>=3 ?'active':'']" v-if="dvyType == 3">
						<view class="select"></view>
						<view class="des">{{i18n.merchantDelivery}}</view>
					</view>
					<view :class="['item',status==4||status==5?'active':'']">
						<view class="select"></view>
						<view class="des">{{i18n.transactionComplete}}</view>
					</view>
				</view>
			</view>

			<!-- 配送地址 -->
			<view class="address-box" v-if="(dvyType == 1 || dvyType == 4) && userAddrDto">
				<view class="img">
					<image src="/static/images/icon/addr.png"></image>
				</view>
				<view class="user-info">
					<view class="name">{{userAddrDto.receiver}}</view>
					<view class="phone">{{userAddrDto.mobile}}</view>
				</view>
				<view class="address-detail">{{userAddrDto.province}}{{userAddrDto.city}}{{userAddrDto.area}}{{userAddrDto.addr}}</view>
			</view>

			<!-- 自提地址 -->
			<view class="delivery-certificate" v-if="dvyType == 2">
				<view class="tit"><text v-if="status == 2 ">{{i18n.deliveryVoucher}}</text><text v-if="status > 2">{{i18n.pickup}}</text></view>
				<view class="address">
					<view class="text">{{stationAddress}}</view>
					<view class="icon-box">
						<view class="icon" @tap="callStation">
							<image src="/static/images/icon/phone.png"></image>
						</view>
						<view class="icon bl" @tap="openMap">
							<image src="/static/images/icon/addr.png"></image>
						</view>
					</view>
				</view>
				<!-- 没付款时 -->
				<view class="code-box no-code" v-if="status == 1">
					<view class="text-box">
						<view class="item">
							<view class="i-lable">{{i18n.pickingCode}}：</view>
							<view class="i-text fw">{{stationCode?stationCode:i18n.deliveryCodeTips}}</view>
						</view>
						<view class="item">
							<view class="i-lable">{{i18n.picker}}：</view>
							<view class="i-text">
								<text>{{stationUserName}}</text>
								<text>{{stationUserMobile}}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 已付款时 -->
				<view class="code-box code-det" @tap="viewCertificate" v-if="status == 2">
					<view class="code">
						<image :src="stationQrCode"></image>
						<!-- <canvas class="qrcode-img" canvas-id="orderQrcode"></canvas> -->
					</view>
					<view class="text-box">
						<view class="item">
							<view class="i-lable">{{i18n.pickingCode}}：</view>
							<view class="i-text fw">{{stationCode}}</view>
						</view>
						<view class="item">
							<view class="i-lable">{{i18n.picker}}：</view>
							<view class="i-text">
								<text>{{stationUserName}}</text>
								<text>{{stationUserMobile}}</text>
							</view>
						</view>
						<view class="item">
							<view class="i-lable">{{i18n.appointmentTime}}：</view>
							<view class="i-text">{{stationTime}}</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 商品信息 -->
			<view class="prod-item">
				<!-- 店铺 -->
				<view class="shop-box">
					<view class="shop-icon">
						<image src="/static/images/icon/shop.png"></image>
					</view>
					<view class="shop-name">{{shopName}}</view>
				</view>
				<!-- /店铺 -->
				<view v-for="(item, prodId) in orderItemDtos" :key="prodId">
					<view class="item-cont" @tap="toProdPage" :data-prodid="item.prodId">
						<view class="prod-pic">
							<image :src="item.pic"></image>
						</view>
						<!-- 拼团商品展示icon -->
						<view class="prod-info">
							<view class="prodname">
								<view class="text">{{item.prodName}}</view>
							</view>
							<view class="suk-con">
								<view class="a-icon" v-if="orderType">{{['',i18n.aGroup,i18n.spike,i18n.integral][orderType]}}</view>
								<view class="sku-name">{{item.skuName}}</view>
							</view>
							<view class="price-nums">
								<view class="prodprice"><text v-if="item.price" class="symbol">￥</text>
									<text v-if="item.price" class="big-num">{{wxs.parsePrice(item.price)[0]}}</text>
									<text v-if="item.price" class="small-num">.{{wxs.parsePrice(item.price)[1]}}</text>
									<text v-if="item.price && orderType==3" class="small-num">+</text>
									<text class="small-num" v-if="orderType==3">{{item.useScore}} {{i18n.integral}}</text>
								</view>
								<view class="number">{{item.prodCount}}{{i18n.piece}}</view>
							</view>
						</view>
						<!-- 申请退款btn -->
						<view class="apply-refund-btn" @tap.stop="applyRefund(item,2)" v-if="!item.refundSn && canRefund && orderType <1">{{i18n.requestRefund}}</view>
						<view class="apply-refund-btn" @tap.stop="viewRefund" :data-refundsn="item.refundSn" v-if="item.refundSn && item.returnMoneySts != -1">{{i18n.checkRefund}}</view>
						<!-- 申请退款btn -->
					</view>
				</view>
			</view>

			<!-- 订单信息 -->
			<view class="order-msg">
				<view class="msg-item">
					<view class="item">
						<text class="item-tit">{{i18n.orderNumber}}：</text>
						<text class="item-txt">{{orderNumber}}</text>
						<!--  #ifdef  APP-PLUS -->
						<text class="copy-btn" @tap="copyBtn">{{i18n.copy}}</text>
						<!--  #endif -->
					</view>
					<view class="item">
						<text class="item-tit">{{i18n.orderTime}}：</text>
						<text class="item-txt">{{createTime}}</text>
					</view>
					<!-- <view class="item">
						<text class="item-tit">物流信息：</text>
						<text class="item-txt">第三个第三个梵蒂冈是</text>
					</view> -->
				</view>
				<view class="msg-item">
					<view class="item">
						<text class="item-tit">{{i18n.paymentMethod}}：</text>
						<text class="item-txt">{{[i18n.integralPayment,i18n.payWithWeChat,i18n.PayWithAli,i18n.payWithWeChat,i18n.payWithWeChat,i18n.payWithWeChat,i18n.PayWithAli,i18n.PayWithAli,i18n.payWithWeChat,i18n.balancePay,i18n.paypalPay][payType]}}</text>
					</view>
					<view class="item">
						<text class="item-tit">{{i18n.deliveryMethod}}：</text>
						<!-- 1卖家配送 2到店自提 3无需快递 4同城配送 -->
						<text class="item-txt">{{['',i18n.sellerDelivery,i18n.pickStore,i18n.merchantDelivery,i18n.sameDelivery][dvyType]}}</text>
					</view>
				</view>
				<view class="msg-item">
					<view class="item">
						<text class="item-tit">{{i18n.OrderNotes}}：</text>
						<text class="item-txt">{{remarks?remarks:''}}</text>
					</view>
				</view>
			</view>

			<view class="order-msg payment">
				<view class="msg-item">
					<view class="item">
						<view class="item-tit">{{i18n.comTotal}}：</view>
						<view class="item-txt">￥{{wxs.parsePrice(productTotalAmount)[0]}}.{{wxs.parsePrice(productTotalAmount)[1]}}</view>
					</view>
					<view class="item">
						<view class="item-tit">{{i18n.shipping}}：</view>
						<view class="item-txt">￥{{wxs.parsePrice(transfee)[0]}}.{{wxs.parsePrice(transfee)[1]}}</view>
					</view>
					<view class="item">
						<view class="item-tit"><text class="item-tit" v-if="orderType && orderType!=3">{{orderType==1?i18n.groupBuy:i18n.spike}}</text>{{i18n.preferential}}：</view>
						<view class="item-txt">-￥{{wxs.parsePrice(reduceAmount)[0]}}.{{wxs.parsePrice(reduceAmount)[1]}}</view>
					</view>
					<view class="item price">
						<view class="item-txt">
							<text class="gray">{{i18n.orderTotal}}：</text>
							<text class="symbol" v-if="actualTotal && actualTotal > 0">￥</text>
							<text class="big-num" v-if="actualTotal && actualTotal > 0">{{wxs.parsePrice(actualTotal)[0]}}</text>
							<text class="small-num" v-if="actualTotal && actualTotal > 0 || actualTotal > 0">.{{wxs.parsePrice(actualTotal)[1]}}</text>
							<text class="small-num" v-if="(actualTotal && actualTotal > 0) && (orderType==3 || orderScore > 0)">+</text>
							<text class="big-num" v-if="orderType==3 || orderScore > 0">{{orderScore}}<text class="small-num">{{i18n.integral}}</text></text>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部栏 -->
      <!-- v-if="canAllRefund && orderType!=3" -->

		</scroll-view>
		<view class="order-detail-footer" >
			<view class="group-det" @tap="handleCustomService">联系客服</view>
			<view class="refund-full" data-refundtype="1" @tap.stop="applyRefund(null,1)" v-if="canAllRefund && orderType!=3" >{{orderType < 1 ? i18n.wholeOrderRefund : i18n.requestRefund}}</view>
			<view  v-if="orderType==1&& status>1 && status!=6" class="group-det" @tap="toGroupDetails" :data-ordernumber="orderNumber">{{i18n.viewGroupDetails}}</view>
		</view>
	</view>
</template>

<script module="wxs" lang="wxs" src="@/wxs/number.wxs"></script>

<script>
	var http = require("@/utils/http.js");
	var Qr = require("@/utils/wxqrcode");
	var util = require("@/utils/util.js");

export default {
  data () {
    return {
      orderItemDtos: [],
      remarks: "",
      actualTotal: 0,
      userAddrDto: null,
      shopId: "", //店铺id
      orderNumber: "",
      createTime: "",
      status: 0,
      productTotalAmount: '',
      transfee: '',
			freeTransfee: '',
      reduceAmount: '',
      prodid: '',
      orderType: 0,
      shopName: '', //店铺名称
      canRefund: false, // 能否退款
      canAllRefund: false, // 能否增单退款
      isLastProd: false, //最后一款商品
      irrevocable: false, //不可撤销
      sum: [], //本单已申请单个退款的商品数组
      dvyType: 1, //配送类型 1:快递 2:自提 3：无需快递

      id: 0, // 自提信息id
      stationAddress: '', // 自提点的地址
      stationCode: '', // 提货码
      stationId: 0, // 自提点id
      stationPhone: '', // 自提点的联系电话
      stationTime: '', // 自提时间(用户下单时选择)
      stationUserMobile: '', // 自提人的手机
      stationUserName: '', // 自提人的名字
      stationQrCode: '', // 提货码二维码
      stationName: '', // 自提点名称

      payType: '', //订单支付类型
      orderScore: 0, // 整单使用积分
      lat:'', //经度
      lng:'' //纬度
    };
  },

  components: {},
  props: {},
  computed: {
    i18n () {
      return this.$t('index')
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
		if (options.orderNum) {
			this.orderNumber = options.orderNum
		}
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 加载导航标题
    uni.setNavigationBarTitle({
      title: this.i18n.orderDetails
    });
    this.loadOrderDetail(this.orderNumber)  //请求订单详情数据

    this.setData({
      isLastProd: false
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
  methods: {
    //跳转商品详情页
    toProdPage: function (e) {
      util.tapLog(3)
      var prodid = e.currentTarget.dataset.prodid;

      if (this.orderType == 3) {
        uni.navigateTo({
          url: '/packageMemberIntegral/pages/convertProdDet/convertProdDet?prodId=' + prodid
        });
      } else {
        this.$Router.push({ path: '/packageProduct/pages/prod/prod', query: { prodid: prodid } })
      }
    },

    /**
   * 是否最后一个商品在执行单个商品退款事件
   */
    lastProdApplyRefund: function () {
      if (this.status == 2) { //待发货状态下
        // 遍历商品list
        if (this.orderItemDtos.length > 1) {  //如果商品列表长度大于1
          let sum = []
          this.orderItemDtos.forEach((el, index) => {
            if (el.refundSn) { //如果拥有退款单号
              sum.push(el)
              this.setData({
                sum
              })
            }
          })
          if (this.sum.length == this.orderItemDtos.length - 1) {
            // 如果拥有退款单号的item等于商品列表数据长度-1，那么点击的这件商品就是最后一件商品
            this.setData({
              isLastProd: true
            })
          } else if (this.sum.length == this.orderItemDtos.length) {
            // 如果拥有退款单号的item等于商品列表数据长度，那么不可撤销申请
            this.setData({
              irrevocable: true  //不可撤销
            })
          }
        };
      }
    },

    /**
     * 申请退款
     */
    applyRefund: util.throttle(function (item, refundtype) {
      util.tapLog(3)
      // refundType 退款类型 1整单  2单个物品
      let status = this.status
      var type = this.status == 2 ? '1' : '2'
      this.loadOrderDetail(this.orderNumber)  //请求订单详情数据
      if (refundtype == 1) { //整单退款
        var items = {}
        items.orderNumber = this.orderNumber;
        items.actualTotal = this.actualTotal; // 订单总额
        items.transfee = this.transfee; // 订单运费
				items.freeTransfee = this.freeTransfee, //运费减免
        items.status = this.status; //订单状态
        items.orderItemDtos = this.orderItemDtos;
        items.orderScore = this.orderScore,  // 整单积分
          // 将数据存储到本地
          wx.setStorageSync("refundItem", items);
      } else if (refundtype == 2) { //单个商品退款
        this.lastProdApplyRefund() //是否最后一个商品执行单个商品退款
        if (this.orderItemDtos.length == 1) { // 是否只有一件商品
          item.isOnlyProd = true
        } else {
          item.isOnlyProd = false
        }
        // 将数据存储到本地
        item.orderNumber = this.orderNumber;
        item.transfee = this.transfee; // 本单运费
				item.freeTransfee = this.freeTransfee, //运费减免
        item.status = this.status; //订单状态
        item.isLastProd = this.isLastProd ? this.isLastProd : undefined // 是否最后一款商品
        //拿到存储在本地的订单项数据
        wx.setStorageSync("refundItem", item);
      }
      /**  判断跳转页面（根据订单是否已发货）*/
      if (status == 2) {   //待发货，直接跳转到申请页，不需要选择退货方式
        uni.navigateTo({ //通过uni.redirectTo实现跳转（关闭当前页面，跳转到应用内某个页面）
          url: `/packageUser/pages/applyRefund/applyRefund?type=${type}&refundType=${refundtype}`,
        })
      } else {  //已发货，跳转到选择退货方式页
        uni.navigateTo({
          url: '/packageUser/pages/chooseRefundWay/chooseRefundWay?refundType=' + refundtype
        })
      }
    }, 600),

    /**
     * 查看退款
     */
    viewRefund: function (e) {
      util.tapLog(3)
      var refundSn = e.currentTarget.dataset.refundsn;
      this.lastProdApplyRefund() //是否最后一个商品执行单个商品退款
      uni.navigateTo({
        url: '/pages/DetailsOfRefund/DetailsOfRefund?refundSn=' + refundSn + '&irrevocable=' + this.irrevocable
      })
    },

    /**
     * 加载订单数据
     */
    loadOrderDetail: function (orderNum) {
      var ths = this;
      uni.showLoading(); //加载订单详情

      var params = {
        url: "/p/myOrder/orderDetail",
        method: "GET",
        data: {
          orderNumber: orderNum
        },
        callBack: function (res) {
          ths.setData({
            shopId: res.shopId,
            orderNumber: orderNum,
            actualTotal: res.actualTotal,
            //实际支付总额（商品总额+运费)
            userAddrDto: res.userAddrDto,
            remarks: res.remarks,
            orderItemDtos: res.orderItemDtos,
            createTime: res.createTime,
            status: res.status,
            productTotalAmount: res.total,
            //所有商品总额
            transfee: res.transfee,
            //运费
						freeTransfee: res.freeTransfee,//运费减免
            reduceAmount: res.reduceAmount,
            orderType: res.orderType,
            shopName: res.shopName,
            canRefund: res.canRefund,
            canAllRefund: res.canAllRefund,
            payType: res.payType,
            dvyType: res.dvyType, // 配送类型 1:快递 2:自提 3：无需快递
            orderScore: res.orderScore, // 整单使用积分
          });
          if (res.dvyType == 2) {
            ths.loadStationDetail(orderNum)
          }
          uni.hideLoading()
        }
      };
      http.request(params);
    },

    /**
     * 加载订单详情自提信息
     */
    loadStationDetail: function (orderNum) {
      uni.showLoading(); //加载订单详情
      var params = {
        url: "/p/myStationOrder/stationDetail",
        method: "GET",
        data: {
          orderNumber: orderNum
        },
        callBack: (res) => {
          uni.hideLoading()
          this.id = res.id, // 自提信息id
            this.stationAddress = res.stationAddress, // 自提点的地址
            this.stationCode = res.stationCode, // 提货码
            this.stationId = res.stationId, // 自提点id
            this.stationPhone = res.stationPhone, // 自提点的联系电话
            this.stationTime = res.stationTime, // 自提时间(用户下单时选择)
            this.stationUserMobile = res.stationUserMobile, // 自提人的手机
            this.stationUserName = res.stationUserName, // 自提人的名字
            this.stationName = res.stationName, // 自提点名称
            this.lat = this.bMapTransQQMap(res.lng, res.lat).lat, // 纬度
            this.lng = this.bMapTransQQMap(res.lng, res.lat).lng, // 经度
            console.log(this.lat,this.lng,'sda')
            this.getQrcode(this.stationCode)
        }
      };
      http.request(params);
    },

    /**
     * 拨打自提点电话
     */
    callStation: function () {
      util.tapLog(3)
      uni.makePhoneCall({
        // 手机号
        phoneNumber: this.stationPhone,
        // 成功回调
        success: (res) => {
        },
        // 失败回调
        fail: (res) => {
        }
      });
    },

    // 将百度地图经纬度转换为腾讯/高德地图经纬度
    bMapTransQQMap: function (lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta);
      let lats = z * Math.sin(theta);
      return {
        lng: lngs,
        lat: lats
      }
    },

    /**
     * 打开地图
     */
    openMap: function () {
      util.tapLog(3)
      var ths = this
      console.log('success',ths.lat,ths.lng);
      uni.openLocation({
        latitude: Number(ths.lat),
        longitude: Number(ths.lng),
        success: function () {
        }
      });
    },

    /**
     * 生成二维码
     */
    getQrcode: function (stationCode) {
      this.stationQrCode = Qr.createQrCodeImg(stationCode)
    },

    // #ifdef  APP-PLUS
    /**
     * 一键复制事件
     */
    // 设置系统剪贴板的内容。
    copyBtn () {
      util.tapLog(3)
      // 除了h5以外都可用的复制方法
      uni.setClipboardData({
        data: this.orderNumber,
        success: function () {
          uni.showToast({
            title: this.i18n.copySucceeded,
            icon: 'none',
            duration: 1000
          })
        }
      });
    },
    // #endif

    // 查看提货凭证
    viewCertificate () {
      util.tapLog(3)
      var cont = {
        stationCode: this.stationCode, // 提货码
        stationAddress: this.stationAddress, // 自提点的地址
        stationPhone: this.stationPhone, // 自提点的联系电话
        stationTime: this.stationTime, // 自提时间(用户下单时选择)
        orderNumber: this.orderNumber, // 订单编号
        stationName: this.stationName
      }
      uni.setStorageSync('stationCont', cont)
      uni.navigateTo({
        url: '/packageUser/pages/deliveryCertificate/deliveryCertificate'
      })
    },
    /**
     * 查看团购详情
     */
    toGroupDetails: function (e) {
      util.tapLog(3)
      uni.navigateTo({
        url: '/packageActivities/pages/spellGroupDetails/spellGroupDetails?orderNumber=' + e.currentTarget.dataset.ordernumber,
      });
    },

    /**
     * 咨询客服
     */
    handleCustomService() {
      console.log(this.shopId);
      util.checkAuthInfo(() => {
        uni.navigateTo({
          url: '/packageUser/pages/chat/chatIm?shopid=' + (this.shopId?this.shopId:'0') + '&orderNumber=' + this.orderNumber
        });
      })
    },

  }
};
</script>
<style>
@import "./order-detail.css";
</style>
